var fs = require("fs"),
    path = require("path"),
//process.argv An array containing the command line arguments.
// The first element will be 'node', the second element will be the name of the JavaScript file.
// The next elements will be any additional command line arguments.
    args = process.argv.splice(2),
    command = args.shift(),
    taskDesc = args.join(" "),
    //process.cwd() returns the current working directory.
    file = path.join(process.cwd(),"/task.text");

console.log("args: "+args);
console.log("command: "+command);

switch (command) {
    case "list":
        listTasks(file);
        break;
    case "add":
        addTask(file,taskDesc);
        break;
    default :
        console.log("Usage: "+ process.argv[0] + " list | add description");
        break;
}

function loadOrInitializeTasksArray(file,cb){
    fs.exists(file,function(exists){
        var tasks = [];
        if (exists) {
            fs.readFile(file,function(err,data){
                if(err) throw err;
                var data = data.toString();
                var tasks = JSON.parse(data);
                cb(tasks);
            });
        }else {
            cb([]);
        }
    });
}

function listTasks(file){
    loadOrInitializeTasksArray(file,function(tasks){
        for (var i in tasks){
            console.log(tasks[i]);
        }
    });
}

function storeTasks(file,tasks){
    fs.writeFile(file,JSON.stringify(tasks),"utf8",function(err){
        console.log("Saved!");
    });
}

function addTask(file,taskDesc){
    loadOrInitializeTasksArray(file,function(tasks){
        tasks.push(taskDesc);
        storeTasks(file,tasks);
    });
}